<template>
  <div class="subpage">
    <div class="topContent">
      <img src="/static/images/pay_success.png" alt />
      <p>付款给：{{ payMsg.payee }}</p>
      <p>
        支付金额：
        <span>￥</span>
        <span>{{price}}</span>
      </p>
    </div>
    <div class="textContent">
      <p>
        <span class="titile">订单金额：</span>
        <span class="text">{{ payMsg.pay_value }}</span>
      </p>
      <p>
        <span class="titile">{{ payway }}：</span>
        <span class="text">{{ payMsg.pay_value }}</span>
      </p>
      <p>
        <span class="titile">付款方式：</span>
        <span class="text">{{ payway }}</span>
      </p>
      <!-- <p>
        <span class="titile">付款账户：</span>
        <span class="text">￥4800</span>
      </p>-->
      <p>
        <span class="titile">订单信息：</span>
        <span class="text orderInfo ">{{ payMsg.orderinfostr }}</span>
        <span>{{strLength}}项</span>
      </p>
      <!-- <p>
        <span class="titile">账户余额：</span>
        <span class="text">￥4800</span>
      </p>-->
    </div>
    <div class="textBtn" @click="topay" v-if="nopay">
      <p>立即支付</p>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      order_id: "",
      orderId: "",
      sum: "",
      way: "",
      payway: "",
      payMsg: {
        orderinfostr: ''
      },
      nopay: true,
      price: "",
      strLength: '',
      unload: false
    };
  },
  onShow() {
    this.nopay = true;
    let obj = {}
    obj = wx.getEnterOptionsSync()
    console.log(wx.getEnterOptionsSync(),'小程序启动参数')
    // 1038 为 其他小程序跳转来启动
    if(obj.scene && obj.scene == 1038 && this.way != "1" && mpvue.getStorageSync('insuranceOrderId')) {
      this.queryInsuranceStatus()
    }
  },
  onLoad(options) {
    Object.assign(this.$data, this.$options.data())
    this.orderId = options.orderId;
    this.nopay = true;
    this.sum = options.sum;
    this.way = options.way;
    if (this.way == "1") {
      this.payway = "现金支付";
    } else {
      this.payway = "医保支付";
    }
    this.getDetail();
  },
  onUnload() {
    console.log('小程序页面退出，处方支付页面')
    this.unload = true
  },
  mounted() {},
  methods: {
    getDetail() {
      //
      var that = this;
      this.$api
        .orderPayItemDetail({ order_id: this.orderId }, { showLoading: true })
        .then(res => {
          // if(res.code==0){
          that.payMsg = res.data;
          that.strLength = that.payMsg.orderinfostr.substring(that.payMsg.orderinfostr.length - 4)
          that.strLength = that.strLength.replace(/[^0-9]/ig, '')
          that.payMsg.orderinfostr = that.payMsg.orderinfostr.slice(0, -5).replace(/\./ig, '')
          that.strLength = that.payMsg.orderinfostr.length > 7 ? '...等' + that.strLength : '共' + that.strLength
          if (res.data.pay_value) {
            var value = res.data.pay_value.slice(1);
            that.price = value;
          }
        });
    },
    queryInsuranceStatus() {
      let that = this
      wx.showLoading({
        title: "加载中...",
        mask: true
      });
      var index = 0;
      let orderId = mpvue.getStorageSync('insuranceOrderId')
      function circleQuery(index) {
        that.$api
          .appointmentPayResultGet(
            { order_id: orderId },
            { showLoading: false }
          )
          .then(temp => {
            mpvue.showLoading({
              title: "加载中...",
              mask: true
            });
            if(that.unload) {
              wx.hideLoading();
              index = 10;
              mpvue.removeStorage({key: 'insuranceOrderId'})
              return
            }
            if (temp.data.pay_status == true) {
                wx.hideLoading();
                mpvue.removeStorage({key: 'insuranceOrderId'})
                that.$router.push(
                  `/pages/center/child/payResult/main?result=1&sum=${
                    that.price
                  }&payee=${'武汉大学人民医院（湖北省人民医院）'}&way=2`
                );
                return;
              }
            if(index > 4) {
              if (temp.data.pay_status == true) {
                wx.hideLoading();
                mpvue.removeStorage({key: 'insuranceOrderId'})
                that.$router.push(
                  `/pages/center/child/payResult/main?result=1&sum=${
                    that.price
                  }&payee=${'武汉大学人民医院（湖北省人民医院）'}&way=2`
                );
                return;
              } else {
                wx.hideLoading();
                mpvue.removeStorage({key: 'insuranceOrderId'})
                that.$router.push(
                  `/pages/center/child/payResult/main?result=2
            &way=1}`
                );
                return;
              }
            }
            index++;
            setTimeout(() => {
                circleQuery(index)
            }, 1000);
            console.log(index, "医保");
          });
      }
      circleQuery(index)
    },
    topay() {
      var that = this;
      if (this.way == "1") {
        //现金
        //支付
        let index = 0;
        let that = this;
        this.$api
          .orderPayWechatMini({ order_id: this.orderId }, { showLoading: true })
          .then(res => {           
            wx.requestPayment({
              timeStamp: res.data.signMp.timeStamp,
              nonceStr: res.data.signMp.nonceStr,
              package: res.data.signMp.package,
              signType: res.data.signMp.signType,
              paySign: res.data.signMp.sign,
              success(data) {
                wx.showLoading({
                  title: "加载中...",
                  mask: true
                });
                console.log('走成功')
                let index = 0;
                function circleQuery(index) {
                  that.$api
                    .appointmentPayResultGet(
                      { order_id: that.orderId },
                      { showLoading: false }
                    )
                    .then(temp => {
                      wx.showLoading({
                        title: "加载中...",
                        mask: true
                      });
                      if(that.unload) {
                        wx.hideLoading();
                        index = 10;
                        return
                      }
                      if (temp.data.pay_status == true) {
                        wx.hideLoading();
                        that.$router.push(
                          `/pages/center/child/payResult/main?result=1&sum=${
                            that.price
                          }&payee=${res.data.payee}&way=1`
                        );
                        that.nopay = false;
                        return;
                      }
                      console.log(index)
                      if (index > 4) {
                        if (temp.data.pay_status == true) {
                          wx.hideLoading();
                          that.$router.push(
                            `/pages/center/child/payResult/main?result=1&sum=${
                              that.price
                            }&payee=${res.data.payee}&way=1`
                          );
                          that.nopay = false;
                          return;
                        } else {
                          wx.hideLoading();
                          that.$router.push(
                            `/pages/center/child/payResult/main?result=2
                        &way=1}`
                          );
                          return;
                        }
                      }
                      index++;
                      setTimeout(() => {
                        circleQuery(index);
                      }, 1000);

                    });
                }
                circleQuery(index)
              },
              fail(res) {
                console.log('走失败')
                wx.showLoading({
                  title: "加载中...",
                  mask: true
                });
                let tip = "支付失败";
                var index = 0;

                function circleQuery(index) {
                  that.$api
                    .appointmentPayResultGet(
                      { order_id: that.orderId },
                      { showLoading: false }
                    )
                    .then(temp => {
                      wx.showLoading({
                        title: "加载中...",
                        mask: true
                      });
                      if(that.unload) {
                        wx.hideLoading();
                        index = 10;
                        return
                      }
                      if (temp.data.pay_status == true) {
                        wx.hideLoading();
                        that.$router.push(
                          `/pages/center/child/payResult/main?result=1&sum=${
                            that.price
                          }&payee=${res.data.payee}&way=1`
                        );
                        that.nopay = false;
                        return;
                      }
                      console.log(index)
                      if (index > 2) {
                        if (temp.data.pay_status == true) {
                          wx.hideLoading();
                          that.$router.push(
                            `/pages/center/child/payResult/main?result=1&sum=${
                              that.price
                            }&payee=${res.data.payee}&way=1`
                          );
                          that.nopay = false;
                          return;
                        } else {
                          wx.hideLoading();
                          that.$router.push(
                            `/pages/center/child/payResult/main?result=2
                        &way=1}`
                          );
                          return;
                        }
                      }
                      index++;
                      setTimeout(() => {
                        circleQuery(index);
                      }, 1000);
                    });
                }
                circleQuery(index)
              }
            });
          });
      } else {
        //医保
        var step = this.$storage.getCardeStatus();
        console.log("step", step);
        this.$api
          .payinsuranceUnifiedorder(
            { order_id: this.orderId, ordersum: this.sum },
            { showLoading: true }
          )
          .then(res => {
            if (res.code == 0) {
              // wx.navigateToMiniProgram(Object ,object)
              wx.navigateToMiniProgram({
                appId: res.data.pay_appid,
                path: res.data.pay_url,
                success(data) {
                  // that.$utils.showToast("text", "支付成功");
                  console.log("success回调，打开loading");
                  console.log('data',data)
                  mpvue.setStorageSync('insuranceOrderId',that.orderId)
                
                },
                fail(data) {
                  console.log("fail回调，打开loading");
                  wx.showLoading({
                    title: "加载中...",
                    mask: true
                  });
                  var index = 0;
                  function circleQuery(index) {
                    that.$api
                      .appointmentPayResultGet(
                        { order_id: that.orderId },
                        { showLoading: false }
                      )
                      .then(temp => {
                        mpvue.showLoading({
                          title: "加载中...",
                          mask: true
                        });
                        if(that.unload) {
                          wx.hideLoading();
                          mpvue.removeStorage({key: 'insuranceOrderId'})
                          index = 10;
                          return
                        }
                        if (temp.data.pay_status == true) {
                            wx.hideLoading();
                            mpvue.removeStorage({key: 'insuranceOrderId'})
                            that.$router.push(
                              `/pages/center/child/payResult/main?result=1&sum=${
                                that.price
                              }&payee=${res.data.beneficiary}&way=2`
                            );
                            return;
                          }
                        if(index > 1) {
                          if (temp.data.pay_status == true) {
                            wx.hideLoading();
                            mpvue.removeStorage({key: 'insuranceOrderId'})
                            that.$router.push(
                              `/pages/center/child/payResult/main?result=1&sum=${
                                that.price
                              }&payee=${res.data.beneficiary}&way=2`
                            );
                            return;
                          } else {
                            wx.hideLoading();
                            mpvue.removeStorage({key: 'insuranceOrderId'})
                            that.$router.push(
                              `/pages/center/child/payResult/main?result=2
                        &way=1}`
                            );
                            return;
                          }
                        }
                        index++;
                        setTimeout(() => {
                            circleQuery(index)
                        }, 1000);
                        console.log(index, "医保");
                      });
                  }
                  circleQuery(index)
                },
              });
            } else {
              that.$router.push(
                `/pages/center/child/payResult/main?result=2&res=${res.msg}`
              );
            }
          });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.subpage {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  // justify-content: center;
  .topContent {
    width: 85%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    // margin: 60rpx 0;
    margin-top: 60rpx;
    padding-bottom: 60rpx;
    border-bottom: 1rpx solid #e9e9e9;
    font-weight: 300;
    img {
      width: 305rpx;
      height: 200rpx;
    }
    p {
      width: 110%;
      margin-top: 45rpx;
      line-height: 40rpx;
      //   margin: 10rpx 0;
      font-size: 30rpx;
      color: #333;
      text-align: center;
      span {
        color: #ff5453;
      }
      span:nth-child(1) {
        font-size: 30rpx;
      }
      span:nth-child(2) {
        font-size: 40rpx;
      }
    }
  }
  .textContent {
    width: 80%;
    // padding: 0 30rpx;
    padding-left: 120rpx;
    font-size: 30rpx;
    margin-top: 100rpx;
    display: flex;
    justify-self: start;
    flex-direction: column;
    p {
      line-height: 72rpx;
      .titile {
        width: 150rpx;
        color: #666;
        font-size: 30rpx;
        text-align: right;
        margin-right: 20rpx;
      }
      .text {
        flex: 1;
        color: #333;
        font-size: 30rpx;
      }
      .orderInfo {
        display: inline-block;
        vertical-align: top; // 处理baseline位移情况
        overflow: hidden;
        max-width: 200rpx;
        height: 50rpx;
      }
    }
  }
  .textBtn {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    bottom: 40rpx;
    p {
      width: 90%;
      height: 100rpx;
      // background-color: #4759e7;
      background: linear-gradient(
        90deg,
        rgba(85, 125, 245, 1) 0%,
        rgba(63, 74, 222, 1) 100%
      );
      text-align: center;
      line-height: 100rpx;
      color: #fff;
    }
  }
}
</style>
